layui.define(['jquery', 'form', 'layer', 'popup', 'dropdown', 'flow', 'table', 'element'], function (exports) {

    var $ = layui.$,
        layer = layui.layer,
        popup = layui.popup,
        dropdown = layui.dropdown,
        table = layui.table,
        flow = layui.flow,
        element = layui.element,
        form = layui.form;


    var tableBar = {
        //表头按钮
        toolbar: function (obj = {}) {
            obj["add"] = obj["add"] || `<button type="button" class="layui-btn layui-btn-normal layui-btn-xs" kllxs-on="kl-add">添加</button>`;
            obj["dels"] = obj["dels"] || `<button type="button" class="layui-btn layui-bg-red layui-btn-xs" kllxs-on="kl-dels">批量删除</button>`;
            obj["recycled"] = obj["recycled"] || `<button type="button" class="layui-btn layui-bg-orange layui-btn-xs" kllxs-on="kl-recycled">回收站</button>`;
            var html = "";
            $.each(obj, function (k, v) {
                html += v;
            })
            return `<div>${html}</div>`;
        },
        // 更多 
        more: function (kllxs_on = "kl-more") {
            return `<div>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" data-info='{{= JSON.stringify(d)}}' kllxs-on="${kllxs_on}">
                            更多
                            <i class="layui-icon layui-icon-down"></i>
                        </button>
                    </div>`;
        },
        // 更多
        // switch滑块
        switch: function (name = "switch",
            title = "是|否",
            data = "1|0",
            kllxs_on = "kl-switch") {
            var arr_data = data.split("|");
            return `<div><div class="layui-form">
                {{# var info = JSON.stringify(d);}}
                {{# if(d.${name}=="${arr_data[0]}") { }}
                <input type="checkbox" name="${name}" title="${title}" data-val="${data}" lay-filter="${kllxs_on}" data-info='{{= info }}' checked lay-skin="switch">
                {{# }else{ }}
                <input type="checkbox" name="${name}" title="${title}" data-val="${data}" lay-filter="${kllxs_on}" data-info='{{= info }}' lay-skin="switch">
                {{# } }}
            </div></div>`;
        },
        // number数字
        number: function (name = "number", tips = "数字", kllxs_on = "kl-number") {
            return `<div class="layui-form">
                <input type="number" name="${name}" kllxs-on="${kllxs_on}" data-info='{{= JSON.stringify(d)}}' placeholder="${tips}" class="layui-input" value='{{=d.${name}}}' >
            </div>`;
        },
        // 文件file 
        file: function (name = "url", photos = false, kllxs_on = "kl-file") {
            if (photos) {
                return `<div><i class="layui-icon layui-icon-carousel" kllxs-on="${kllxs_on}" data-photos="{{= d.${name}}}" onmouseover="layer.tips('点击查看', this);"></i></div>`
            } else {
                return `<div><div class="lazyimg">
                    {{# var info = JSON.stringify(d),fn;}}
                    {{# var extension = d.${name}.substring(d.${name}.lastIndexOf('.') + 1);}}
                    {{# var imageExtensions = ['jpg', 'jpeg', 'png', 'gif'];}}
                    {{# if(imageExtensions.indexOf(extension.toLowerCase()) !== -1) { }}
                    <img class="kl-table-img" lay-src='{{= d.${name}}}' data-photos="{{= d.${name}}}" kllxs-on="${kllxs_on}" onmouseover="layer.tips('点击查看', this);" />
                    {{# }else{ }}
                    <a href="{{= d.${name}}}" target="_blank" onmouseover="layer.tips('点击下载', this);">{{= d.${name}}}</a>
                    {{# } }}
                </div>`
            }
        },
        // 表头右侧按钮
        defaultToolbar: function (obj = []) {
            if (obj.length === 0) {
                return ['filter', 'print', 'exports', {
                    title: '搜索',
                    layEvent: 'kl-search',
                    icon: 'layui-icon-search'
                }]
            }
        },
        // 表搜索回调 
        tableSearch: function (arr, obj = {}) {
            var html = "";
            $.each(arr[0], function (k, v) {
                if (v.field && v.search) {
                    obj[v.field] = obj[v.field] || `<input type="text" name="${v.field}" placeholder="请输入${v.title}" class="layui-input">`
                    html += `<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">${v.title}</label>
                            <div class="layui-input-block">
                                ${obj[v.field]}
                            </div>
                        </div>
                    </div>`;
                }
            })
            if (html != "") {
                $("#kl-search-form").html(`<div class="layui-collapse" style="margin-bottom: 10px;" lay-filter="kl-search-collapse">
                    <div class="layui-colla-item">
                        <div class="layui-colla-title">搜索信息</div>
                        <div class="layui-colla-content">
                            <form class="layui-form layui-form-pane" action="">
                                <div class="layui-row layui-col-space15">
                                ${html}
                                <div class="layui-col-xs12">
                                    <div class="layui-form-item">
                                        <button class="layui-btn" lay-submit lay-filter="kl-table-search">确认</button>
                                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                    </div>
                                </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>`)
            }
            element.render('collapse', 'kl-search-collapse')
            form.render(null, 'kl-search-form')
        },
        // 表回调函数默认
        tableDone: function (res, curr, count, origin) {
            // 配合图片懒加载
            flow.lazyimg({
                elem: '.lazyimg img'
            });
        },
        // 事件处理
        util: function (url, obj = {}) {
            // 表头添加事件
            obj["kl-add"] = obj["kl-add"] || function () {
                popup.iframe(url.add)
            }
            $('body').delegate('[kllxs-on="kl-add"]', 'click', obj["kl-add"])
            // 表头批量删除事件
            obj["kl-dels"] = obj["kl-dels"] || function () {
                var checkStatus = table.checkStatus("table")
                var data = checkStatus.data; // 获取选中的数据
                if (data.length !== 0) {
                    var id = [];
                    $.each(data, function (k, v) {
                        id.push(v.id)
                    })
                    popup.confirm(url.del, { id })
                } else {
                    popup.msg({ code: 0, msg: "请选择数据", fun: function () { } })
                }
            }
            $('body').delegate('[kllxs-on="kl-dels"]', 'click', obj["kl-dels"])
            // 表头回收站事件 kllxs-on="kl-recycled"
            $('body').delegate('[kllxs-on="kl-recycled"]', 'click', function () {
                popup.iframe(url.recycled)
            })
            //表排序
            obj["table-sort"] = obj["table-sort"] || function (obj) {
                table.reload('table', {
                    initSort: obj, // 记录初始排序，如果不设的话，将无法标记表头的排序状态。
                    where: { // 请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        order: {
                            field: obj.field, // 排序字段
                            order: obj.type // 排序方式
                        }
                    }
                });
            }
            table.on('sort(table)', obj["table-sort"])
            // 滑块事件
            obj["kl-switch"] = obj["kl-switch"] || function (data) {
                var info = JSON.parse($(data.elem).attr("data-info"))
                var name = $(data.elem).attr("name")
                var arr = $(data.elem).attr("data-val").split('|')

                if (info[name] == arr[0]) {
                    info[name] = arr[1]
                } else {
                    info[name] = arr[0]
                }
                $.post(url.edit, info, function (res) {
                    layer.msg(res.msg)
                    $(data.elem).attr("data-info", JSON.stringify(info))
                })
            }
            form.on('switch(kl-switch)', obj["kl-switch"])
            // number数字事件
            obj["kl-number"] = obj["kl-number"] || function () {
                var then = $(this)
                var info = JSON.parse(then.attr("data-info"))
                var name = then.attr("name")
                info[name] = then.val()
                $.post(url.edit, info, function (res) {
                    layer.msg(res.msg)
                    then.attr("data-info", JSON.stringify(info))
                })
            }
            $('body').delegate('input[kllxs-on="kl-number"]', 'change', obj["kl-number"])
            // more更多事件
            obj["kl-more"] = obj["kl-more"] || function () {
                var info = JSON.parse($(this).attr("data-info"))
                dropdown.render({
                    elem: this, // 绑定元素选择器，此处指向 class 可同时绑定多个元素
                    show: true,
                    data: [{
                        title: '编辑',
                        id: "edit"
                    }, {
                        title: '删除',
                        id: "del"
                    }],
                    click: function (obj) {
                        if (obj.id === "edit") {
                            popup.iframe(`${url.edit}?id=${info.id}`)
                        } else {
                            popup.confirm(`${url.del}`, { id: info.id })
                        }
                    }
                });
            }
            $('body').delegate('button[kllxs-on="kl-more"]', 'click', obj["kl-more"])
            // 打开相册
            obj["kl-file"] = obj["kl-file"] || function () {
                var info = $(this).attr("data-photos")
                var imgArr = info.split(",")
                var data = []
                $.each(imgArr, function (k, v) {
                    data.push({
                        alt: `相片${k + 1}`,
                        pid: k,
                        src: v
                    })
                })
                popup.photos(data)
            }
            $('body').delegate('[kllxs-on="kl-file"]', 'click', obj["kl-file"])
            //表头按钮控件
            obj["kl-toolbar"] = obj["kl-toolbar"] || function (obj) {
                // console.log(obj)
                if (obj.event == "kl-search") {
                    console.log($('[lay-filter="kl-search-collapse"] .layui-colla-item'))
                    $('[lay-filter="kl-search-collapse"] .layui-colla-title').click()
                }
            }
            table.on('toolbar(table)', obj["kl-toolbar"])
            //搜索表单设置
            form.on('submit(kl-table-search)', function (data) {
                var field = data.field; // 获取表单全部字段值
                table.reload('table', {
                    page: {
                        curr: 1 // 重新从第 1 页开始
                    },
                    where: { where: field } // 搜索的字段
                });
                return false; // 阻止默认 form 跳转
            })
        }
    }

    exports('tableBar', tableBar); // 输出模块
})